package com.hiray.taglayoutmanager;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class RecyclerViewActivity extends AppCompatActivity {

    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    private List<String> datas = new ArrayList<>();
    private LinearAdapter adapter;
    private int index = 0;
    private LinearLayoutManager layoutManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recycler_view);
        ButterKnife.bind(this);
        setSupportActionBar(toolbar);
        work();
    }

    private void work() {
        layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
//        layoutManager.setItemPrefetchEnabled(false);
        recyclerView.setLayoutManager(layoutManager);
        layoutManager.setStackFromEnd(false);
        adapter = new LinearAdapter();
        adapter.setCallBack(new LinearAdapter.CallBack() {
            @Override
            public void onClick(int pos) {
//                delItem(pos);
            }
        });
        prepareData();
        adapter.setDatas(datas);
        recyclerView.setAdapter(adapter);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.add_del_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_del:
                delItem(0);
                break;
            case R.id.menu_add_header:
                addItem(0);
                break;
            case R.id.menu_add_mid:
                addItem(1);
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void addItem(int pos) {
        datas.add(pos, String.valueOf(--index));
        adapter.notifyItemInserted(pos);
    }

    private void delItem(int pos) {
//        datas.set(4, "4->6");
//        datas.set(6, "4");o
////        adapter.notifyItemMoved(4, 6);
//        pos = layoutManager.findFirstVisibleItemPosition() + 1;
        if (datas.isEmpty())
            return;
        datas.remove(pos);
        adapter.notifyItemRemoved(pos);
    }

    private void prepareData() {
        for (int i = 0; i < 20; i++) {
            datas.add(String.valueOf(i));
        }
    }
}
